<template>
  <el-row :gutter="20">
    <el-col :offset="6" :span="12">
      <el-divider content-position="left">{{ `${updateDoto ? '修改' : '添加'}代办事项` }}</el-divider>
    </el-col>
  </el-row>
  <el-row :gutter="20">
    <el-col :offset="6" :span="10">
      <el-form ref="addDotoRef" :rules="rules" :model="form" label-width="130px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" style="width: 300px;" />
        </el-form-item>
        <el-form-item v-for="(item, index) in form.project" :key="index" :label="`项目${index + 1}`">
          <el-row :gutter="20">
            <el-col :span="10">
              <el-input v-model="item.project" />
            </el-col>
            <el-col :span="12">
              <el-input v-model="item.branch" />
            </el-col>
            <el-col :span="2">
              <el-button type="danger" :icon="Delete" :disabled="index == 0" @click.prevent="removeProject(item)"
                circle />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button @click="addProject">添加项目</el-button>
        </el-form-item>
        <el-form-item class="shixiang_content" v-for="(item, index) in form.desc" :key="index" :label="`事项${index + 1}`">
          <el-row :gutter="20">
            <el-col :span="19">
              <el-input autosize type="textarea" v-model="item.desc" />
            </el-col>
            <el-col :span="3">
              <el-switch v-model="item.isFinish" />
            </el-col>
            <el-col :span="2">
              <el-button type="danger" :icon="Delete" :disabled="index == 0" @click.prevent="removeDesc(item)" circle />
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-checkbox-group v-model="item.project">
                <div v-for="(item, index) in form.project" :key="index">
                  <el-checkbox v-show="!!item.project" :label="item.project">
                    {{ item.project }}
                  </el-checkbox>
                </div>
              </el-checkbox-group>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button @click="addDesc">添加事项</el-button>
        </el-form-item>
        <el-form-item label="组别" prop="group">
          <el-select v-model="form.group" allow-create filterable default-first-option :reserve-keyword="false"
            placeholder="请选择组别">
            <el-option v-for="group in dotoStore.groupList" :key="group" :label="group" :value="group" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否完成" prop="isFinish">
          <el-switch v-model="form.isFinish" />
        </el-form-item>
        <el-form-item label="是否发版" prop="isRelease">
          <el-switch v-model="form.isRelease" />
        </el-form-item>
        <el-form-item label="是否标记" prop="isFlag">
          <el-switch v-model="form.isFlag" />
        </el-form-item>
        <el-form-item style="margin-left: 100px;">
          <el-button type="info" @click="back">返回</el-button>
          <el-button type="primary" @click="submitForm(addDotoRef)">提交</el-button>
          <el-button v-show="!updateDoto" @click="resetForm(addDotoRef)">清空</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>
<script setup lang="ts">
import { Desc } from '@/types/card';
import { Card, Project } from '@/types/card';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { Delete } from '@element-plus/icons-vue'
import { onBeforeMount, reactive, ref } from 'vue';
import { useDotoStore } from '@/stores/dotoStore'
import { ordObj } from "@/utils/util"
import { useRouter, useRoute } from "vue-router"

const route = useRoute()
const dotoStore = useDotoStore()
onBeforeMount(() => {
  dotoStore.initGroupList()
})

// 表单数据
let form = reactive<Card>({
  title: '',
  project: reactive<Array<Project>>([{ project: '', branch: '' }]),
  desc: reactive<Array<Desc>>([{ desc: '', project: [], isFinish: false }]),
  group: ''
})
const updateDoto = ref<boolean>(false)
onBeforeMount(() => {
  if (route.query.doto) {
    const doto = dotoStore.findDoto(route.query.doto)
    if (!doto) {
      router.go(-2)
    } else {
      form = doto
      updateDoto.value = true
    }
  }
})

const rules = reactive<FormRules<Card>>({
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 4, max: 20, message: '长度限制在[4-20]', trigger: 'blur' }
  ],
  project: [
    { required: true, message: '请添加项目', trigger: 'blur' }
  ],
  desc: [
    { required: true, message: '请添加事项', trigger: 'blur' }
  ]
})

// 项目
const addProject = () => {
  form.project.push({
    project: '',
    branch: ''
  })
}
const removeProject = (item: Project) => {
  const index = form.project.indexOf(item)
  if (index !== -1) {
    form.project.splice(index, 1)
  }
}

// 事项
const addDesc = () => {
  form.desc.push({
    desc: '',
    project: [],
    isFinish: false
  })
}
const removeDesc = (item: Desc) => {
  const index = form.desc.indexOf(item)
  if (index !== -1) {
    form.desc.splice(index, 1)
  }
}

// 返回
const router = useRouter()
const back = () => {
  router.back()
}

// 提交
const addDotoRef = ref<FormInstance>()
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid: any) => {
    if (!valid) return
    const unValidProject = form.project.reduce((count, project) => {
      if (!project.project || !project.branch)
        return count += 1
      return count
    }, 0)
    if (unValidProject > 0) {
      ElMessage({
        dangerouslyUseHTMLString: true,
        message: '<strong><i>项目</i> 必输</strong>',
        type: 'error'
      })
      return
    }
    const unValidDesc = form.desc.reduce((count, desc) => {
      if (!desc.desc || desc.project.length < 1)
        return count += 1
      return count
    }, 0)
    if (unValidDesc > 0) {
      ElMessage({
        dangerouslyUseHTMLString: true,
        message: '<strong><i>事项</i> 必输</strong>',
        type: 'error'
      })
      return
    }
    form.desc.forEach(desc => {
      desc.descn = desc.desc.replace(/\n/g, '<br>')
    })
    if (!updateDoto.value) {
      dotoStore.addDoto(ordObj(form))
    } else {
      dotoStore.updateDoto(ordObj(form))
      router.back()
    }
    resetForm(formEl)
    ElMessage({
      dangerouslyUseHTMLString: true,
      message: `<strong><i>${updateDoto.value ? '修改' : '添加'}成功</i></strong>`,
      type: 'success'
    })
  })
}

// 清空
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  form.project = reactive<Array<Project>>([{ project: '', branch: '' }])
  form.desc = reactive<Array<Desc>>([{ desc: '', project: [], isFinish: false }])
}

</script>
<style>
.shixiang_content .el-form-item__content {
  display: block;
}
</style>